package com.mls.wms.android.widget.outwh;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.http.RequestManager;
import com.google.zxing.client.android.Intents;
import com.google.zxing.client.android.activity.WmsCaptureActivity;
import com.mls.wms.android.R;
import com.mls.wms.android.adapter.SimpleDropDownAdapter;
import com.mls.wms.android.constant.ScanTypeConstants;
import com.mls.wms.android.constant.ServicePort;
import com.mls.wms.android.extend.AnimDialogFragment;
import com.mls.wms.android.extend.BaseActivity;
import com.mls.wms.android.model.DropDownItemModel;
import com.mls.wms.android.model.ResponseResult;

import org.json.JSONObject;

import java.util.List;
import java.util.Map;

/**
 * Created by 2014-400 on 2015-09-07.
 */
public class TransferActivity extends BaseActivity {
    private EditText etTransferNo;
    private Spinner spCarrier;
    private EditText etExpressNo;
    private EditText etScanQty;
    private Button btnSubmit;

    private boolean isCamera = false;
    private int transferNo = 0;
    private String carrierNo = "";
    private List<DropDownItemModel> listSpinner;
    private SimpleDropDownAdapter adapter;

    private AnimDialogFragment progressDialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_outwh_transfer);

        //弹出框
        progressDialog = new AnimDialogFragment();
        progressDialog.setResId(R.drawable.anim_progress_dialog);

        btnSubmit = (Button) this.findViewById(R.id.act_outwh_transfer_btn_submit);
        etTransferNo = (EditText) this.findViewById(R.id.act_outwh_transfer_transfer_no);
        spCarrier = (Spinner) this.findViewById(R.id.act_outwh_transfer_carrier_name);
        etExpressNo = (EditText) this.findViewById(R.id.act_outwh_transfer_express_no);
        etScanQty = (EditText) this.findViewById(R.id.act_outwh_transfer_scan_qty);
        etScanQty.setText("0");

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doSubmit();
            }
        });

        spCarrier.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                carrierNo = listSpinner.get(position).getValue();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                carrierNo = "";
            }
        });

        etExpressNo.setSelectAllOnFocus(true);
        etExpressNo.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    doSubmit();
                    return true;
                }
                return false;
            }
        });
        etExpressNo.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    doSubmit();
                    return true;
                }
                return false;
            }
        });

        this.initTransferNo();
        this.initSpinnerCarrier();
    }

    private void initTransferNo() {
        get(ServicePort.getUrl(ServicePort.GetVehicleNo), null, new RequestManager.RequestListener() {
            @Override
            public void onRequest() {

            }

            @Override
            public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                try {
                    ResponseResult result = new ResponseResult();
                    result = result.parseJson(s);
                    if (result != null && result.getSuc() == true) {
                        transferNo = Integer.parseInt(result.getResult().toString());
                        etTransferNo.setText(transferNo + "");
                    } else {
                        String message = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                        Toast.makeText(TransferActivity.this, message, Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(TransferActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(String s, String s2, int i) {
                Toast.makeText(TransferActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        }, 1);
    }

    /**
     * 初始化下拉框数据
     */
    private void initSpinnerCarrier() {
        get(ServicePort.getUrl(ServicePort.GetCarrierInfo), null, new RequestManager.RequestListener() {
            @Override
            public void onRequest() {

            }

            @Override
            public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                try {
                    ResponseResult result = new ResponseResult();
                    result = result.parseJson(s);
                    if (result != null && result.getSuc() == true) {
                        DropDownItemModel model = new DropDownItemModel();

                        listSpinner = model.parseJsons(result.getResult().toString());

                        adapter = new SimpleDropDownAdapter(TransferActivity.this, listSpinner);
                        spCarrier.setAdapter(adapter);
                    } else {
                        String message = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                        Toast.makeText(TransferActivity.this, message, Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(TransferActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(String s, String s2, int i) {
                Toast.makeText(TransferActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        }, 1);
    }

    private boolean checkSubmit() {
        if (this.transferNo <= 0) {
            showDialog(R.string.dialog_msg_transfer_no_error, this.etExpressNo);
            return false;
        } else if (TextUtils.isEmpty(this.carrierNo)) {
            showDialog(R.string.dialog_msg_carrier_not_null, this.etExpressNo);
            return false;
        } else if (TextUtils.isEmpty(this.etExpressNo.getText().toString().trim())) {
            showDialog(R.string.dialog_msg_express_no_not_null, this.etExpressNo);
            return false;
        }

        return true;
    }

    private void doSubmit() {
        if (true == this.checkSubmit()) {
            progressDialog.show(getFragmentManager(), this.toString());
            JSONObject data = new JSONObject();
            try {
                data.put("carrierReferNo", this.etExpressNo.getText().toString().trim());
                data.put("vehicleno", this.transferNo);
                data.put("carrierCode", this.carrierNo);
                data.put("type", 4);
            } catch (Exception e) {
                e.printStackTrace();
            }

            put(ServicePort.getUrl(ServicePort.Delivery), data, new RequestManager.RequestListener() {
                @Override
                public void onRequest() {

                }

                @Override
                public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                    String errorMsg = "";
                    try {
                        ResponseResult result = new ResponseResult();
                        result = result.parseJson(s);
                        if (result != null && result.getSuc() == true) {
                            etExpressNo.setText("");
                            etExpressNo.requestFocus();

                            //增加扫描数量
                            int qty = 1 + Integer.parseInt(etScanQty.getText().toString());
                            etScanQty.setText(qty + "");

                            //第一个成功之后锁定承运商
                            spCarrier.setEnabled(false);

                            progressDialog.dismiss();

                            //继续扫描
                            if (isCamera == true) {
                                isCamera = false;
                                Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                                intent.addCategory(Intent.ACTION_MEDIA_SCANNER_STARTED);
                                intent.setClass(TransferActivity.this, WmsCaptureActivity.class);
                                startActivityForResult(intent, ScanTypeConstants.SCAN_BAR_CODE);
                            }

                            return;
                        } else {
                            errorMsg = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        errorMsg = e.getMessage();
                    }

                    if (false == TextUtils.isEmpty(errorMsg)) {
                        progressDialog.dismiss();
                        showDialog(errorMsg, etExpressNo);
                    }

                }

                @Override
                public void onError(String s, String s2, int i) {
                    progressDialog.dismiss();
                    showDialog(s, etExpressNo);
                }
            }, 1);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ScanTypeConstants.SCAN_BAR_CODE:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    this.etExpressNo.setText(bundle.getString(Intents.Scan.RESULT, ""));
                    this.etExpressNo.requestFocus();

                    isCamera = true;
                    this.doSubmit();
                }
            default:
                break;
        }
    }

    @Override
    public int getTopNameResId() {
        return R.string.title_text_outwh_transfer;
    }
}
